//
//  DataModel.swift
//  account
//
//  Created by Qingke on 16/5/5.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit
import CoreData
class DataModel {
    var appDel: AppDelegate!
    var context: NSManagedObjectContext!
    let userDefault = NSUserDefaults.standardUserDefaults()
    var monthOutlay: Double 
    var monthIncome: Double
    var monthCha: Double {
            return monthIncome - monthOutlay
    }
    var income: Double
    var outlay: Double
    var calendar: String
    var items = [CustomerLtem]()
    
    init() {
        monthOutlay = userDefault.doubleForKey("Moutlay")
        print(monthOutlay)
        monthIncome = userDefault.doubleForKey("Mincome")
        income = userDefault.doubleForKey("income")
        outlay = userDefault.doubleForKey("outlay")
        calendar = userDefault.objectForKey("Calendar") as? String ?? "数据为空"
        loadData()
        appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        context = appDel.managedObjectContext
    }
    
    
    func saveData() {
        userDefault.setValue(income, forKey: "income")
        userDefault.setValue(outlay , forKey: "outlay")
        userDefault.setDouble(monthOutlay, forKey: "Moutlay")
        userDefault.setDouble(monthIncome, forKey: "Mincome")
        //userDefault.setObject(calendar, forKey: "Calendar")  这里是由于重新保存相关内容，时候回取代上次保存的数据。
        //原因是重构的时候出现的。由于在重构时候已经离开了 当时的工作环境，对流程的理解忘记了导致，一次重构就出现了很大的问题。
        
    }
    
    func saveDataByCoreData(id: Int , number: Double ,tip: String , itemName: String ) {
        let account = NSEntityDescription.insertNewObjectForEntityForName ("Account", inManagedObjectContext: context )
        //account.setValue(NSDate(), forKey: "date")
        account.setValue(id, forKey: "id")
        account.setValue(number, forKey: "number")
        account.setValue(tip, forKey: "tip")
        account.setValue(itemName, forKey: "item")
        do {
            try context.save()
            let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            print("paths")
            print(paths)
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //print("Unresolved error \(error), \(error.userInfo)")
        }

    }
    
    
    func dataPath() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let filePath = paths[0] as NSString
        print(filePath)
        return filePath.stringByAppendingPathComponent("CustomerLtems.plist")//"categorylist.plist"
    }
    
    
    func saveItems() {
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(items, forKey: "items")
        archiver.finishEncoding()
        data.writeToFile(dataPath(), atomically: true)
        print("保存成功")
        
    }
    
    func loadData() {
        let data = NSData(contentsOfFile: dataPath())
        if let data = data {
            let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
            items = unarchiver.decodeObjectForKey("items") as! [CustomerLtem]
            print(items.count)
            unarchiver.finishDecoding()
            
            print("加载完成")
        }
    }
    
}
